<template>
  <div class="max-w-4xl mx-auto p-4">
    <a-card>
      <a-typography-title :level="2">计算工具</a-typography-title>
      
      <a-tabs v-model:activeKey="activeTab">
        <!-- 科学计算器 -->
        <a-tab-pane key="calculator" tab="科学计算器">
          <div class="calculator-container">
            <a-input
              v-model:value="display"
              class="mb-4 text-right text-xl"
              readonly
            />
            
            <div class="grid grid-cols-5 gap-2">
              <!-- 函数按钮 -->
              <a-button @click="appendFunction('sin(')" class="function-btn">sin</a-button>
              <a-button @click="appendFunction('cos(')" class="function-btn">cos</a-button>
              <a-button @click="appendFunction('tan(')" class="function-btn">tan</a-button>
              <a-button @click="appendFunction('log(')" class="function-btn">log</a-button>
              <a-button @click="appendFunction('ln(')" class="function-btn">ln</a-button>
              
              <a-button @click="appendFunction('sqrt(')" class="function-btn">√</a-button>
              <a-button @click="appendFunction('pow(')" class="function-btn">x^n</a-button>
              <a-button @click="appendConstant('PI')" class="function-btn">π</a-button>
              <a-button @click="appendConstant('E')" class="function-btn">e</a-button>
              <a-button @click="appendOperator('!')" class="function-btn">!</a-button>

              <!-- 数字和运算符 -->
              <a-button @click="appendNumber('7')">7</a-button>
              <a-button @click="appendNumber('8')">8</a-button>
              <a-button @click="appendNumber('9')">9</a-button>
              <a-button @click="appendOperator('/')" type="primary">/</a-button>
              <a-button @click="clearEntry()" type="primary">CE</a-button>

              <a-button @click="appendNumber('4')">4</a-button>
              <a-button @click="appendNumber('5')">5</a-button>
              <a-button @click="appendNumber('6')">6</a-button>
              <a-button @click="appendOperator('*')" type="primary">×</a-button>
              <a-button @click="clearAll()" type="primary">C</a-button>

              <a-button @click="appendNumber('1')">1</a-button>
              <a-button @click="appendNumber('2')">2</a-button>
              <a-button @click="appendNumber('3')">3</a-button>
              <a-button @click="appendOperator('-')" type="primary">-</a-button>
              <a-button @click="backspace()" type="primary">←</a-button>

              <a-button @click="appendNumber('0')">0</a-button>
              <a-button @click="appendNumber('.')">.</a-button>
              <a-button @click="toggleSign()">±</a-button>
              <a-button @click="appendOperator('+')" type="primary">+</a-button>
              <a-button @click="calculate()" type="primary">=</a-button>
            </div>

            <a-divider>计算历史</a-divider>
            
            <div class="history-container max-h-40 overflow-y-auto">
              <a-list size="small" :data-source="history">
                <template #renderItem="{ item }">
                  <a-list-item>
                    <div class="flex justify-between w-full">
                      <span>{{ item.expression }}</span>
                      <span class="font-bold">= {{ item.result }}</span>
                    </div>
                  </a-list-item>
                </template>
              </a-list>
            </div>
          </div>
        </a-tab-pane>

        <!-- 单位转换器 -->
        <a-tab-pane key="converter" tab="单位转换器">
          <a-form layout="vertical">
            <a-form-item label="转换类型">
              <a-select v-model:value="converterType">
                <a-select-option value="length">长度</a-select-option>
                <a-select-option value="area">面积</a-select-option>
                <a-select-option value="volume">体积</a-select-option>
                <a-select-option value="weight">重量</a-select-option>
                <a-select-option value="temperature">温度</a-select-option>
                <a-select-option value="time">时间</a-select-option>
                <a-select-option value="speed">速度</a-select-option>
                <a-select-option value="data">数据大小</a-select-option>
              </a-select>
            </a-form-item>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
              <a-form-item label="从">
                <div class="flex gap-2">
                  <a-input-number
                    v-model:value="fromValue"
                    style="width: 160px"
                    :precision="precision"
                  />
                  <a-select
                    v-model:value="fromUnit"
                    style="width: 120px"
                    :options="unitOptions"
                  />
                </div>
              </a-form-item>

              <a-form-item label="到">
                <div class="flex gap-2">
                  <a-input-number
                    v-model:value="toValue"
                    style="width: 160px"
                    :precision="precision"
                    readonly
                  />
                  <a-select
                    v-model:value="toUnit"
                    style="width: 120px"
                    :options="unitOptions"
                  />
                </div>
              </a-form-item>
            </div>

            <a-form-item>
              <a-button type="primary" @click="swapUnits">
                交换单位
                <template #icon><swap-outlined /></template>
              </a-button>
            </a-form-item>

            <a-divider>常用转换</a-divider>

            <div class="grid grid-cols-2 md:grid-cols-3 gap-4">
              <a-card v-for="preset in commonConversions" :key="preset.name" size="small" hoverable @click="applyPreset(preset)">
                <div class="text-center">
                  <div>{{ preset.name }}</div>
                  <div class="text-gray-500 text-sm">
                    {{ preset.from }} → {{ preset.to }}
                  </div>
                </div>
              </a-card>
            </div>
          </a-form>
        </a-tab-pane>
      </a-tabs>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { message } from 'ant-design-vue';
import { SwapOutlined } from '@ant-design/icons-vue';

// 标签页
const activeTab = ref('calculator');

// 科学计算器
const display = ref('0');
const history = ref<{ expression: string; result: string }[]>([]);
const lastResult = ref('');

// 计算器函数
const appendNumber = (num: string) => {
  if (display.value === '0' && num !== '.') {
    display.value = num;
  } else {
    display.value += num;
  }
};

const appendOperator = (op: string) => {
  display.value += op;
};

const appendFunction = (func: string) => {
  display.value += func;
};

const appendConstant = (constant: string) => {
  const constants: Record<string, number> = {
    'PI': Math.PI,
    'E': Math.E
  };
  display.value += constants[constant];
};

const clearEntry = () => {
  display.value = '0';
};

const clearAll = () => {
  display.value = '0';
  lastResult.value = '';
};

const backspace = () => {
  display.value = display.value.slice(0, -1) || '0';
};

const toggleSign = () => {
  if (display.value.startsWith('-')) {
    display.value = display.value.slice(1);
  } else {
    display.value = '-' + display.value;
  }
};

const calculate = () => {
  try {
    // 替换数学函数
    let expression = display.value
      .replace(/sin\(/g, 'Math.sin(')
      .replace(/cos\(/g, 'Math.cos(')
      .replace(/tan\(/g, 'Math.tan(')
      .replace(/log\(/g, 'Math.log10(')
      .replace(/ln\(/g, 'Math.log(')
      .replace(/sqrt\(/g, 'Math.sqrt(')
      .replace(/pow\(/g, 'Math.pow(')
      .replace(/PI/g, 'Math.PI')
      .replace(/E/g, 'Math.E');

    // 处理阶乘
    expression = expression.replace(/(\d+)!/g, (match, num) => {
      let result = 1;
      for (let i = 2; i <= parseInt(num); i++) {
        result *= i;
      }
      return result.toString();
    });

    const result = eval(expression);
    history.value.unshift({
      expression: display.value,
      result: result.toString()
    });
    
    if (history.value.length > 10) {
      history.value.pop();
    }

    lastResult.value = result.toString();
    display.value = result.toString();
  } catch (e) {
    message.error('计算错误');
    console.error('计算错误:', e);
  }
};

// 单位转换器
const converterType = ref('length');
const fromValue = ref(1);
const toValue = ref(0);
const fromUnit = ref('');
const toUnit = ref('');
const precision = ref(4);

// 单位定义
const unitDefinitions = {
  length: {
    m: 1,
    km: 1000,
    cm: 0.01,
    mm: 0.001,
    in: 0.0254,
    ft: 0.3048,
    yd: 0.9144,
    mi: 1609.344
  },
  area: {
    'm²': 1,
    'km²': 1000000,
    'cm²': 0.0001,
    'mm²': 0.000001,
    'ha': 10000,
    'acre': 4046.8564224,
    'in²': 0.00064516,
    'ft²': 0.09290304
  },
  volume: {
    'L': 1,
    'mL': 0.001,
    'm³': 1000,
    'cm³': 0.001,
    'gal': 3.78541,
    'qt': 0.946353,
    'pt': 0.473176,
    'fl oz': 0.0295735
  },
  weight: {
    kg: 1,
    g: 0.001,
    mg: 0.000001,
    lb: 0.45359237,
    oz: 0.028349523125,
    t: 1000
  },
  temperature: {
    '°C': 'C',
    '°F': 'F',
    'K': 'K'
  },
  time: {
    s: 1,
    min: 60,
    h: 3600,
    day: 86400,
    week: 604800,
    month: 2592000,
    year: 31536000
  },
  speed: {
    'm/s': 1,
    'km/h': 0.277778,
    'mph': 0.44704,
    'knot': 0.514444
  },
  data: {
    B: 1,
    KB: 1024,
    MB: 1048576,
    GB: 1073741824,
    TB: 1099511627776
  }
};

// 获取当前转换类型的单位选项
const unitOptions = computed(() => {
  const units = Object.keys(unitDefinitions[converterType.value as keyof typeof unitDefinitions]);
  return units.map(unit => ({ value: unit, label: unit }));
});

// 监听值变化进行转换
watch([fromValue, fromUnit, toUnit, converterType], () => {
  if (!fromValue.value || !fromUnit.value || !toUnit.value) return;

  if (converterType.value === 'temperature') {
    // 温度转换特殊处理
    const temp = fromValue.value;
    const from = unitDefinitions.temperature[fromUnit.value as keyof typeof unitDefinitions.temperature];
    const to = unitDefinitions.temperature[toUnit.value as keyof typeof unitDefinitions.temperature];
    
    let celsius;
    // 转换为摄氏度
    switch (from) {
      case 'C': celsius = temp; break;
      case 'F': celsius = (temp - 32) * 5/9; break;
      case 'K': celsius = temp - 273.15; break;
    }
    
    // 从摄氏度转换为目标单位
    switch (to) {
      case 'C': toValue.value = celsius; break;
      case 'F': toValue.value = celsius * 9/5 + 32; break;
      case 'K': toValue.value = celsius + 273.15; break;
    }
  } else {
    // 其他单位转换
    const units = unitDefinitions[converterType.value as keyof typeof unitDefinitions];
    const fromFactor = units[fromUnit.value as keyof typeof units] as number;
    const toFactor = units[toUnit.value as keyof typeof units] as number;
    toValue.value = (fromValue.value * fromFactor) / toFactor;
  }
});

// 初始化单位选择
watch(converterType, (newType) => {
  const units = Object.keys(unitDefinitions[newType as keyof typeof unitDefinitions]);
  fromUnit.value = units[0];
  toUnit.value = units[1];
});

// 交换单位
const swapUnits = () => {
  const tempUnit = fromUnit.value;
  fromUnit.value = toUnit.value;
  toUnit.value = tempUnit;
};

// 常用转换预设
const commonConversions = computed(() => {
  switch (converterType.value) {
    case 'length':
      return [
        { name: '米转千米', from: 'm', to: 'km' },
        { name: '英里转千米', from: 'mi', to: 'km' },
        { name: '英尺转米', from: 'ft', to: 'm' }
      ];
    case 'weight':
      return [
        { name: '千克转磅', from: 'kg', to: 'lb' },
        { name: '克转盎司', from: 'g', to: 'oz' },
        { name: '吨转千克', from: 't', to: 'kg' }
      ];
    case 'temperature':
      return [
        { name: '摄氏转华氏', from: '°C', to: '°F' },
        { name: '华氏转摄氏', from: '°F', to: '°C' },
        { name: '摄氏转开氏', from: '°C', to: 'K' }
      ];
    default:
      return [];
  }
});

// 应用预设转换
const applyPreset = (preset: { from: string; to: string }) => {
  fromUnit.value = preset.from;
  toUnit.value = preset.to;
};

// 初始化
converterType.value = 'length';
</script>

<style scoped>
.calculator-container {
  max-width: 400px;
  margin: 0 auto;
}

.function-btn {
  font-size: 0.875rem;
}

:deep(.ant-input-number) {
  width: 100%;
}

.history-container {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 8px;
}
</style> 